# ' `.final` function, set names of `foreach` objection.
# '
# ' Automatically inherit names of list or data.table, and rm the rownames of
# ' matrix.
# '
# ' @examples
# ' \dontrun{
# ' .final <- set_names_foreach(.final, .combine)
# ' }
set_names_foreach <- function(.final, .combine, ...){
    if (is.null(.final)) {
        if (missing(.combine)) {
            # for data.frame and list
            y   <- list(...)[[1]]
            y_class <- class(y)
            y_names <- names(y)

            if (!('iter' %in% y_class) && !is.null(y_names) &&
                ( is.list(y) || is.vector(y)) )
            {
                .final <- function(x) { setNames(x, y_names[1:length(x)]) }
            }
        } else {
            # 2. for matrix
            FUN_combine <- match.fun(.combine)
            if (identical(FUN_combine, rbind)) {
                # .final <- function(mat) { `rownames<-`(mat, NULL) }
                ## can't fixed the error of R 3.6.0
                .final = function(mat) {
                    mat2 <- if (is.null(colnames(mat))) {
                        `dimnames<-`(mat, NULL)
                        # `attributes<-`(mat, attributes(mat)[1])
                    } else {
                        `rownames<-`(mat, NULL)
                    }
                    as.matrix(mat2)
                }
            }
        }
    }
    .final
}
